/**
 * 
 */

package cn.cn77.futures;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import cn.cn77.futures.utils.C2Sever;
import cn.cn77.futures.utils.MyApplication;
import cn.cn77.futures.utils.UserSharedPreference;
import cn.cn77.futures.utils.Utils;
import cn.cn77.futures.widget.NavigationBar;

/**
 * @author 振朝 成功率计算页面
 */
public class SuccessRateActivity extends BaseActivity {
	private NavigationBar naviBar;
	private TextView dateTv, delSumTimesTv;
	private ListView successRateLv;
	private String formateDate;
	private ArrayList<HashMap<String, String>> listData = new ArrayList<HashMap<String, String>>();
	/**
	 * 用于显示到ListView中的List数据Key，前五个是服务器返回的数据字段，后三个是需要计算后才有数据的字段
	 */
	private String field[] = {
			C2Sever.Field.SuccessRate.Number, // 序号
			C2Sever.Field.SuccessRate.SumTimes, // 总次数
			C2Sever.Field.SuccessRate.OrderTimes,// 下单次数
			C2Sever.Field.SuccessRate.DelTimes,// 删除次数
			C2Sever.Field.SuccessRate.SuccessTimes,// 成功次数
			"failure", // 失败次数
			"results", // 结果
			"rate", C2Sever.Field.SuccessRate.StartTime,
			C2Sever.Field.SuccessRate.EndTime };// 成功率
	private SimpleAdapter adapter;
	/**
	 * ListView模板中的组件id表
	 */
	private int[] itemsId = { R.id.tv_no, R.id.tv_sum_times,
			R.id.tv_order_times, R.id.tv_del_times, R.id.tv_success_number,
			R.id.tv_failure_times, R.id.tv_results_number,
			R.id.tv_success_rate, R.id.tv_start_time, R.id.tv_end_time };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.success_rate_activity);
		MyApplication.getInstance().addActivity(this);
		setUrl(C2Sever.Controller.SuccessRate, C2Sever.Action.SuccessRate);
		naviBar = (NavigationBar) findViewById(R.id.success_rate_navi_bar);
		naviBar.setTitle("成功率");
		initView();
		formateDate = Utils.getCurrentTime("yyyy-MM-dd");
		dateTv.setText(formateDate);
		mParams.put("mid", UserSharedPreference.getParams(
				UserSharedPreference.USER_ID, this));
		requestData(formateDate);
	}

	/**
	 * 请求网络数据
	 */
	private void requestData(String date) {
		mParams.put(C2Sever.Field.SuccessRate.Date, date);
		doAsyncPost(this);
	}

	@Override
	protected void successWithData(JSONObject data, int status) {
		try {

			dateTv.setText(data.getString(C2Sever.Field.SuccessRate.Date));
			delSumTimesTv.setText(data
					.getString(C2Sever.Field.SuccessRate.SumDelTimes));
			JSONArray jArr = data.getJSONArray(C2Sever.Field.Other);

			paserJSONArray(field, jArr);
			showListView();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void showListView() {
		adapter = new SimpleAdapter(this, listData, R.layout.success_rate_item,
				field, itemsId);
		successRateLv.setAdapter(adapter);
	}

	/**
	 * 处理数据过程： 遍历list 逐个数据进行赋值，然后生成一个可以使用的datalist 需要计算的数据先转换为整型然后再计算，再转换为字符串
	 * 
	 * @param field
	 *            解析数据的key表
	 * @param jArr
	 *            json数组
	 * @throws JSONException
	 */
	private void paserJSONArray(String[] field, JSONArray jArr)
			throws JSONException {
		String number, sumTimes, orderTimes, delTimes, successTimes, failureTimes, results, successRate, startTime, endTime;
		int orderInt, successInt, failureInt, resultInt;
		HashMap<String, String> map;
		JSONObject o;
		for (int index = 0; index < jArr.length(); index++) {
			map = new HashMap<String, String>();
			o = jArr.getJSONObject(index);
			number = o.getString(field[0]);
			sumTimes = o.getString(field[1]);

			orderTimes = o.getString(field[2]);
			orderInt = Integer.valueOf(orderTimes);
			successTimes = o.getString(field[4]);
			successInt = Integer.valueOf(successTimes);
			delTimes = o.getString(field[3]);

			failureInt = orderInt - successInt;
			failureTimes = failureInt + "";

			resultInt = successInt - failureInt;
			if (resultInt > 0) {
				results = "+" + resultInt;
			} else {
				results = "" + resultInt;
			}

			if (orderInt == 0) {
				successRate = "0";
			} else {

				NumberFormat nt = NumberFormat.getPercentInstance();
				nt.setMinimumFractionDigits(2);
				successRate = nt.format((float) successInt / (float) orderInt);
			}
			startTime = o.getString(field[8]);
			endTime = o.getString(field[9]);
			map.put(field[0], number);// 序号
			map.put(field[1], sumTimes);// 总次数
			map.put(field[2], orderTimes);// 下单次数
			map.put(field[3], delTimes);// 删除次数
			map.put(field[4], successTimes);// 成功次数
			map.put(field[5], failureTimes);// 失败次数
			map.put(field[6], results);// 结果
			map.put(field[7], successRate);// 成功率
			map.put(field[8], startTime);
			map.put(field[9], endTime);
			listData.add(map);
		}
	}

	/*
	 * 页面逻辑： 请求所有数据 处理数据 显示数据 过滤器 根据过滤器请求数据
	 */
	private void initView() {
		dateTv = (TextView) findViewById(R.id.tv_date);
		delSumTimesTv = (TextView) findViewById(R.id.tv_del_times);
		successRateLv = (ListView) findViewById(R.id.lv_success_rate);
		successRateLv.setDividerHeight(10);
	}

	/**
	 * 选择日期按钮的监听方法
	 * 
	 * @param v
	 */
	public void chooseDate(View v) {
		// 日期获取之后监听事件
		DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker datePicker, int year, int month,
					int dayOfMonth) {
				formateDate = year + "-" + (month + 1) + "-" + dayOfMonth;
				requestData(formateDate);
			}
		};
		// 用来获取日期和时间的
		Calendar calendar = Calendar.getInstance();
		new DatePickerDialog(this, dateListener, calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH)).show();
	}
}
